<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>视频通话测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial;
            padding: 10px;
            padding-bottom: 200px;
        }
        
        .video-container {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-top: 10px;
        }
        
        .video-wrapper {
            position: relative;
            width: 100%;
            background: #000;
        }
        
        video {
            width: 100%;
            height: auto;
            aspect-ratio: 16/9;
            background: #222;
            border-radius: 8px;
        }
        
        .controls {
            position: fixed;
            bottom: 0;
            left: 0;
            right: 0;
            padding: 15px;
            background: rgba(0,0,0,0.8);
            display: flex;
            flex-direction: column;
            gap: 10px;
            z-index: 100;
        }
        
        .chat-container {
            position: fixed;
            bottom: 140px;
            left: 0;
            right: 0;
            height: 200px;
            background: rgba(0,0,0,0.8);
            padding: 10px;
            display: flex;
            flex-direction: column;
        }
        
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            margin-bottom: 10px;
            color: white;
            font-size: 14px;
        }
        
        .chat-input-group {
            display: flex;
            gap: 10px;
        }
        
        .message {
            padding: 5px;
            margin: 5px 0;
            border-radius: 4px;
            background: rgba(255,255,255,0.1);
        }
        
        .system-message {
            color: #00ff00;
            font-style: italic;
        }
        
        .input-group {
            display: flex;
            gap: 10px;
        }
        
        input {
            flex: 1;
            padding: 12px;
            border: none;
            border-radius: 25px;
            background: rgba(255,255,255,0.9);
            font-size: 16px;
        }
        
        button {
            padding: 12px 20px;
            border: none;
            border-radius: 25px;
            background: #007AFF;
            color: white;
            font-size: 16px;
            font-weight: 500;
            touch-action: manipulation;
        }
        
        button:active {
            background: #0056b3;
        }
        
        @media (min-width: 768px) {
            .video-container {
                flex-direction: row;
                justify-content: space-around;
            }
            
            .video-wrapper {
                width: 48%;
            }
            
            .controls {
                flex-direction: row;
                justify-content: center;
                align-items: center;
            }
            
            .input-group {
                width: auto;
            }
        }
    </style>
</head>
<body>
    <div class="video-container">
        <div class="video-wrapper">
            <h3>本地视频</h3>
            <video id="localVideo" autoplay playsinline muted></video>
        </div>
        <div class="video-wrapper">
            <h3>远程视频</h3>
            <video id="remoteVideo" autoplay playsinline></video>
        </div>
    </div>
    
    <div class="chat-container">
        <div class="chat-messages" id="chatMessages"></div>
        <div class="chat-input-group">
            <input type="text" id="chatInput" placeholder="输入聊天内容">
            <button onclick="sendChat()">发送</button>
        </div>
    </div>
    
    <div class="controls">
        <div class="input-group">
            <input type="text" id="roomId" placeholder="输入房间号">
            <button ontouchstart="joinRoom()" onclick="joinRoom()">加入房间</button>
        </div>
        <div class="input-group">
            <button ontouchstart="startCall()" onclick="startCall()">开始通话</button>
            <button ontouchstart="hangup()" onclick="hangup()">挂断</button>
        </div>
    </div>

    <script>
        let ws;
        let localStream;
        let peerConnection;
        const configuration = {
            iceServers: [{urls: 'stun:stun.l.google.com:19302'}]
        };

        function addMessage(message, isSystem = false) {
            const messagesDiv = document.getElementById('chatMessages');
            const messageElement = document.createElement('div');
            messageElement.className = isSystem ? 'message system-message' : 'message';
            messageElement.textContent = message;
            messagesDiv.appendChild(messageElement);
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

        function sendChat() {
            const input = document.getElementById('chatInput');
            const message = input.value.trim();
            if (message && ws) {
                ws.send(JSON.stringify({
                    type: 'chat',
                    message: message
                }));
                addMessage(`我: ${message}`);
                input.value = '';
            }
        }

        document.getElementById('chatInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendChat();
            }
        });

        async function joinRoom() {
            const roomId = document.getElementById('roomId').value;
            ws = new WebSocket(`ws://localhost:3014/video/${roomId}`);
            
            ws.onopen = () => {
                addMessage('成功加入房间！', true);
            };
            
            ws.onmessage = async function(event) {
                const message = JSON.parse(event.data);
                
                if (message.type === 'offer') {
                    addMessage('收到视频通话请求', true);
                    await handleOffer(message);
                } else if (message.type === 'answer') {
                    await handleAnswer(message);
                } else if (message.type === 'candidate') {
                    await handleCandidate(message);
                } else if (message.type === 'chat') {
                    addMessage(`对方: ${message.message}`);
                }
            };
            
            ws.onclose = () => {
                addMessage('已断开连接', true);
            };
        }

        async function startCall() {
            try {
                localStream = await navigator.mediaDevices.getUserMedia({
                    video: true,
                    audio: true
                });
                document.getElementById('localVideo').srcObject = localStream;

                peerConnection = new RTCPeerConnection(configuration);
                
                localStream.getTracks().forEach(track => {
                    peerConnection.addTrack(track, localStream);
                });

                peerConnection.ontrack = event => {
                    document.getElementById('remoteVideo').srcObject = event.streams[0];
                };

                peerConnection.onicecandidate = event => {
                    if (event.candidate) {
                        ws.send(JSON.stringify({
                            type: 'candidate',
                            candidate: event.candidate
                        }));
                    }
                };

                const offer = await peerConnection.createOffer();
                await peerConnection.setLocalDescription(offer);
                ws.send(JSON.stringify({
                    type: 'offer',
                    offer: offer
                }));

            } catch (err) {
                console.error(err);
            }
        }

        async function handleOffer(message) {
            if (!localStream) {
                localStream = await navigator.mediaDevices.getUserMedia({
                    video: true,
                    audio: true
                });
                document.getElementById('localVideo').srcObject = localStream;
            }

            peerConnection = new RTCPeerConnection(configuration);
            
            localStream.getTracks().forEach(track => {
                peerConnection.addTrack(track, localStream);
            });

            peerConnection.ontrack = event => {
                document.getElementById('remoteVideo').srcObject = event.streams[0];
            };

            peerConnection.onicecandidate = event => {
                if (event.candidate) {
                    ws.send(JSON.stringify({
                        type: 'candidate',
                        candidate: event.candidate
                    }));
                }
            };

            await peerConnection.setRemoteDescription(message.offer);
            const answer = await peerConnection.createAnswer();
            await peerConnection.setLocalDescription(answer);
            
            ws.send(JSON.stringify({
                type: 'answer',
                answer: answer
            }));
        }

        async function handleAnswer(message) {
            await peerConnection.setRemoteDescription(message.answer);
        }

        async function handleCandidate(message) {
            await peerConnection.addIceCandidate(message.candidate);
        }

        function hangup() {
            if (localStream) {
                localStream.getTracks().forEach(track => track.stop());
            }
            if (peerConnection) {
                peerConnection.close();
            }
            if (ws) {
                ws.close();
            }
            document.getElementById('localVideo').srcObject = null;
            document.getElementById('remoteVideo').srcObject = null;
        }
    </script>
</body>
</html>